import Immutable from 'immutable';
import { routerRedux } from 'dva/router';
import toast from '../utils/toast';
import {
  queryInvoiceOrderList,
  queryInfoList,
  addInfo,
  editInfo,
  doInvoice,
  queryInvoiceList,
  sendEmail,
  queryInvoiceUrl,
  queryInvoiceStatus,
  delInfo,
  queryEmail,
} from '../services/invoice';
import { Refuel } from './refuel';
import { save, get } from '../utils/storage';

const InvoiceInfoRecord = Immutable.Record({
  bankBranch: null,
  bankName: null,
  bankNo: null,
  companyAddress: null,
  companyName: null,
  companyTelephone: null,
  infoId: null,
  nickName: null,
  openType: null,
  openTypeDes: null,
  phone: null,
  taxCode: null,
  userId: null,
  selected: false,
});

export class InvoiceInfo extends InvoiceInfoRecord {}

const InvoiceRecord = Immutable.Record({
  openType: null,
  status: null,
  invoiceNum: null,
  invoiceAmountYuan: null,
  rateCountAmountYuan: null,
  createTime: null,
  email: null,
  recordId: null,
  invoiceUrl: null,
  emailHis: {
    company: null,
    personal: null,
  },
});

export class Invoice extends InvoiceRecord {
  static parseOrder(item) {
    return new Invoice({
      ...item,
    });
  }
  getType() {
    if (this.get('openType') === 1) {
      return '个人普票';
    } else {
      return '企业普票';
    }
  }

  canPreview() {
    return [3].includes(this.get('status'));
  }

  getStatus() {
    let result;
    switch (this.get('status')) {
      case 0:
      case 1:
        result = '审核中';
        break;
      case 3:
        result = '已通过';
        break;
      case 5:
        result = '未通过';
        break;
      case 4:
        result = '开票失败';
        break;
      default:
        result = '未知状态';
        break;
    }
    return result;
  }
}

export default {
  namespace: 'invoice',
  state: Immutable.fromJS({
    permission: {
      ready: false,
      enabled: true,
      desc: '发票功能暂不开放',
    },
    orderList: [],
    invoiceInfoList: [],
    userName: '',
    showOrder: true,
    openType: null,
    email: '',
    invoiceList: {
      page: 1,
      hasMore: true,
      list: [],
    },
  }),

  effects: {
    *fetchEmailHis({ payload }, { call, put }) {
      const res = yield call(queryEmail, payload);
      if (res.success) {
        yield put({
          type: 'updateEmailHis',
          payload: res.data,
        });
      }
    },
    *delInfo({ payload }, { call, put }) {
      const res = yield call(delInfo, payload);
      if (res.success) {
        yield put({
          type: 'fetchInfoList',
          payload: {
            openType: 2,
          },
        });
        yield put(routerRedux.goBack());
      }
    },
    *fetchInvoiceStatus({ payload }, { call, put }) {
      const res = yield call(queryInvoiceStatus, payload);
      if (res.success) {
        yield put({
          type: 'updatePermission',
          payload: res.data,
        });
      }
    },
    *fetchUrl({ payload }, { call, put }) {
      const res = yield call(queryInvoiceUrl, payload);
      if (res.success) {
        // window.location.href = 'https://youyuer-private-dev.oss-cn-hangzhou.aliyuncs.com/invoice//invoice/334021814667841536011.pdf?Expires=1561187475&OSSAccessKeyId=LTAISYHz0HAzUqYO&Signature=sEjp9qDkA6PLPCboIFpxU4ltKF8%3D';
        // const url = 'https://youyuer-private-dev.oss-cn-hangzhou.aliyuncs.com/invoice//invoice/334021814667841536011.pdf?Expires=1561187475&OSSAccessKeyId=LTAISYHz0HAzUqYO&Signature=sEjp9qDkA6PLPCboIFpxU4ltKF8%3D';
        const { url } = res.data;
        yield put(routerRedux.push({
          pathname: 'invoicePreview',
          search: `?url=${encodeURIComponent(url)}`,
        }));
      }
    },
    *sendEmail({ payload }, { call, put }) {
      const res = yield call(sendEmail, payload);
      if (res.success) {
        toast('发送成功');
        yield put(routerRedux.goBack());
      }
    },
    *fetchInvoiceList({ payload }, { call, put }) {
      const res = yield call(queryInvoiceList, payload);
      if (res.success) {
        yield put({
          type: 'updateInvoiceList',
          payload: res.data,
        });
      }
    },
    *invoice({ payload }, { call, put }) {
      const res = yield call(doInvoice, payload);
      if (res.success) {
        toast('开票成功！');
        yield put({
          type: 'fetchOrderList',
        });
        yield put(routerRedux.push('invoiceList'));
      }
    },
    *addOrEditInfo({ payload }, { call, put }) {
      const res = yield call((payload.infoId ? editInfo : addInfo), payload);
      if (res.success) {
        yield put({
          type: 'fetchInfoList',
          payload: {
            openType: 2,
          },
        });
        yield put(routerRedux.goBack());
      }
    },
    *fetchOrderListIfNeeded({ payload }, { select, put }) {
      const orderList = yield select(state => state.invoice.get('orderList'));
      if (orderList.size === 0) {
        yield put({
          type: 'fetchOrderList',
          payload,
        });
      }
    },
    *fetchOrderList({ payload }, { call, put }) {
      const res = yield call(queryInvoiceOrderList, payload);
      if (res.success) {
        yield put({
          type: 'updateOrderList',
          payload: res.data,
        });
      }
    },
    *fetchInfoListIfNeeded({ payload }, { select, put }) {
      const infoList = yield select(state => state.invoice.get('invoiceInfoList'));
      if (infoList.size === 0) {
        yield put({
          type: 'fetchInfoList',
          payload,
        });
      }
    },
    *fetchInfoList({ payload }, { call, put }) {
      const res = yield call(queryInfoList, payload);
      if (res.success) {
        yield put({
          type: 'updateInfoList',
          payload: res.data,
        });
      }
    },
  },

  reducers: {
    initData(state) {
      return state.merge({
        userName: '',
        showOrder: true,
        openType: null,
        email: '',
        orderList: state.get('orderList').map(order => order.set('selected', false)),
      });
    },
    updateEmailHis(state, { payload }) {
      return state.mergeIn(['emailHis'], {
        company: payload.companyEmail,
        personal: payload.personEmail,
      });
    },
    updatePermission(state, { payload }) {
      return state.mergeIn(['permission'], {
        ready: true,
        enabled: payload.status === '1',
        desc: payload.content || '发票功能维护中',
      });
    },
    updateInvoiceList(state, { payload }) {
      let list = state.getIn(['invoiceList', 'list']);
      if (payload.targetPage === 1) {
        list = list.clear();
      }

      payload.resultList.forEach((item) => {
        list = list.push(Invoice.parseOrder(item));
      });
      return state.mergeIn(['invoiceList'], {
        hasMore: payload.pageCount > payload.targetPage,
        page: payload.targetPage,
        list,
      });
    },
    selectInfo(state, { payload }) {
      let infoList = state.get('invoiceInfoList');
      infoList = infoList.map(info => info.set('selected', info.get('infoId') === payload.get('infoId')));
      save('invoice_info_id', payload.get('infoId'));
      return state.set('invoiceInfoList', infoList);
    },
    emailChanged(state, { payload }) {
      return state.set('email', payload);
    },
    userNameChanged(state, { payload }) {
      return state.set('userName', payload);
    },
    showOrder(state, { payload }) {
      return state.set('showOrder', payload);
    },
    openTypeChanged(state, { payload }) {
      return state.set('openType', payload);
    },
    updateInfoList(state, { payload }) {
      const infoId = get('invoice_info_id');
      return state.set('invoiceInfoList', Immutable.fromJS(payload.map(item => new InvoiceInfo({
        ...item,
        selected: `${item.infoId}` === `${infoId}`,
      }))));
    },
    selectOrder(state, { payload }) {
      const { index, subIndex } = payload;
      let orderList = state.get('orderList');
      const selected = orderList.getIn([index, 'list', subIndex, 'selected']);
      orderList = orderList.setIn([index, 'list', subIndex, 'selected'], !selected);
      return state.set('orderList', orderList);
    },
    updateOrderList(state, { payload }) {
      let orderList = Immutable.fromJS(payload.map(item => Refuel.parseInvoice(item)));
      orderList = Refuel.groupBy(orderList, 'createTime');
      return state.set('orderList', orderList);
    },
  },
};
